<template>
  <el-container class="dashboard-container" :class="isDark ? 'dark' : ''">
    <SidebarMenu :activeMenu="activeTab" :isDark="isDark" :isCollapsed="isSidebarCollapsed" @select="onMenuSelect" />
    <el-container class="main-container" :class="{ 'sidebar-collapsed': isSidebarCollapsed }">
      <AppHeader :isDark="isDark" :title="headerTitle" :isSidebarCollapsed="isSidebarCollapsed"
        @toggle-theme="toggleTheme" @toggle-sidebar="toggleSidebar" @refresh="refreshPage" />
      <AppTabs :model-value="activeTab" :tabs="tabs" :isDark="isDark" @update:modelValue="val => activeTab = val"
        @remove="removeTab" @tab-click="onTabClick" />
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>
<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useThemeStore } from '../stores/theme'
import SidebarMenu from '../components/SidebarMenu.vue'
import AppHeader from '../components/AppHeader.vue'
import AppTabs from '../components/AppTabs.vue'
import { ElMessage } from 'element-plus'

const themeStore = useThemeStore()
const isDark = computed(() => themeStore.isDark)
const route = useRoute()
const router = useRouter()

const isSidebarCollapsed = ref(false)

const tabs = ref([
  { label: '工作台', name: '/dashboard/workbench', closable: false, parent: '仪表盘' }
])
const activeTab = ref('/dashboard/workbench')

// 菜单项 label 映射（可根据实际菜单结构完善）
const menuLabelMap = {
  '/dashboard/workbench': { label: '工作台', parent: '仪表盘', closable: false },
  '/dashboard/analysis': { label: '分析页', parent: '仪表盘', closable: true },
  '/dashboard/ecommerce': { label: '电子商务', parent: '仪表盘', closable: true },
  '/template/1': { label: '模板1', parent: '模板中心', closable: true },
  '/template/2': { label: '模板2', parent: '模板中心', closable: true },
  '/component/1': { label: '组件1', parent: '组件中心', closable: true },
  '/component/2': { label: '组件2', parent: '组件中心', closable: true },
  '/example/1': { label: '示例1', parent: '功能示例', closable: true },
  '/example/2': { label: '示例2', parent: '功能示例', closable: true },
  '/system/user': { label: '用户管理', parent: '系统管理', closable: true },
  '/system/role': { label: '角色管理', parent: '系统管理', closable: true },
  '/system/permission': { label: '权限管理', parent: '系统管理', closable: true },
  '/article/list': { label: '文章列表', parent: '文章管理', closable: true },
  '/article/edit': { label: '文章编辑', parent: '文章管理', closable: true },
  '/ops/monitor': { label: '监控', parent: '运维管理', closable: true },
  '/ops/log': { label: '日志', parent: '运维管理', closable: true },
  '/help': { label: '帮助中心', closable: true },
  '/changelog': { label: '更新日志', closable: true },
  '/user/profile': { label: '个人中心', parent: '', closable: true }
}

// 初始化时添加工作台标签
onMounted(() => {
  if (!tabs.value.length) {
    tabs.value.push({ label: '工作台', name: '/dashboard/workbench', closable: false, parent: '仪表盘' })
    activeTab.value = '/dashboard/workbench'
  }
})

// 监听路由变化，自动新增标签页
watch(
  () => route.path,
  (path) => {
    if (!menuLabelMap[path]) return
    if (!tabs.value.find(t => t.name === path)) {
      const { label, parent, closable } = menuLabelMap[path]
      tabs.value.push({ label, name: path, closable: closable !== false, parent })
    }
    activeTab.value = path
  },
  { immediate: true }
)

function onMenuSelect(index) {
  router.push(index)
}

function onTabClick(tab) {
  router.push(tab.props.name)
}

function removeTab(targetName) {
  // 禁止移除工作台
  if (targetName === '/dashboard/workbench') return
  const idx = tabs.value.findIndex(t => t.name === targetName)
  if (idx !== -1) {
    tabs.value.splice(idx, 1)
    // 如果关闭的是当前激活标签
    if (activeTab.value === targetName) {
      let nextTab
      if (idx - 1 >= 0) {
        nextTab = tabs.value[idx - 1].name
      } else {
        nextTab = tabs.value[0].name
      }
      router.push(nextTab)
    }
  }
}

const headerTitle = computed(() => {
  const tab = tabs.value.find(t => t.name === activeTab.value)
  if (!tab) return ''
  if (tab.parent) return `${tab.parent} / ${tab.label}`
  return tab.label
})

function toggleTheme() {
  themeStore.toggleTheme()
  setHtmlDark(themeStore.isDark)
  ElMessage.success(themeStore.isDark ? '已切换为深色模式' : '已切换为浅色模式')
}

function toggleSidebar() {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
  ElMessage.success(isSidebarCollapsed.value ? '侧边栏已折叠' : '侧边栏已展开')
}

function refreshPage() {
  window.location.reload()
  ElMessage.success('页面已刷新')
}

function setHtmlDark(dark) {
  document.documentElement.classList.toggle('dark', dark)
}

watch(isDark, (val) => setHtmlDark(val), { immediate: true })
</script>
<style scoped>
.dashboard-container {
  height: 100vh;
  min-height: 100vh;
  width: 100vw;
  min-width: 0;
  box-sizing: border-box;
  background: var(--el-bg-color-menu, var(--el-bg-color, #fff));
}

:deep(.el-container) {
  background: transparent !important;
  border: none !important;
}

:deep(.el-aside) {
  background: transparent !important;
  border: none !important;
}

.dark .dashboard-container,
.dark :deep(.el-container),
.dark :deep(.el-aside) {
  background: var(--el-bg-color-menu, #181a20) !important;
  border: none !important;
}

.main-container {
  display: flex;
  flex-direction: column;
  flex: 1 1 0%;
  min-width: 0;
  height: 100vh;
  min-height: 100vh;
  box-sizing: border-box;
  transition: margin-left 0.3s ease;
}

.main-container.sidebar-collapsed {
  margin-left: 8px;
}

.main-content {
  flex: 1 1 0%;
  min-width: 0;
  min-height: 0;
  padding: 20px;
  background: var(--el-bg-color-page, #f5f7fa);
  box-sizing: border-box;
  overflow: auto;
}

/* 自定义滚动条样式 */
.main-content::-webkit-scrollbar {
  width: 6px;
}

.main-content::-webkit-scrollbar-track {
  background: transparent;
}

.main-content::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.main-content::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}

/* 深色模式下的滚动条 */
.dark .main-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
}

.dark .main-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* 深色模式样式 */
.dark {
  --el-bg-color: #18181c;
  --el-bg-color-page: #141414;
  --el-color-primary: #409EFF;
  --el-text-color-primary: #fff;
  --el-text-color-regular: #e5eaf3;
  --el-border-color: #4c4d4f;
  color: #fff;
}

.dark .main-container {
  background: var(--el-bg-color, #18181c);
}

.dark .main-content {
  background: var(--el-bg-color-page, #141414);
  color: #fff;
}

/* 深色模式下的输入框 */
.dark .el-input__inner {
  background: #1d1d1f !important;
  border-color: #4c4d4f !important;
  color: #e5eaf3 !important;
}

/* 深色模式下的面包屑 */
.dark .el-breadcrumb__item {
  color: #a8abb2 !important;
}

.dark .el-breadcrumb__item:last-child {
  color: #e5eaf3 !important;
}

/* 深色模式下的标签页 */
.dark .el-tabs__item {
  color: #a8abb2 !important;
}

.dark .el-tabs__item.is-active {
  color: #409EFF !important;
}

.dark .el-tabs__nav {
  background: #1d1d1f !important;
}

/* 深色模式下的菜单 */
.dark .el-menu {
  background: #18181c !important;
  border: none !important;
}

.dark .el-menu-item {
  color: #e5eaf3 !important;
  border: none !important;
}

.dark .el-menu-item.is-active {
  color: #409EFF !important;
  background: #1d1d1f !important;
  border: none !important;
}

.dark .el-sub-menu__title {
  color: #e5eaf3 !important;
  border: none !important;
}

/* 移除所有边框 */
.el-menu {
  border: none !important;
}

.el-menu-item {
  border: none !important;
}

.el-sub-menu__title {
  border: none !important;
}
</style>